package top.haichi.webpaper.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.haichi.webpaper.entity.Paper;
import top.haichi.webpaper.entity.Result;
import top.haichi.webpaper.entity.Student;
import top.haichi.webpaper.mapper.PaperMapper;
import top.haichi.webpaper.mapper.StudentMapper;
import top.haichi.webpaper.mapper.TeacherMapper;
import top.haichi.webpaper.service.FileService;
import top.haichi.webpaper.utils.FileUtils;

import java.io.File;
import java.io.IOException;
import java.nio.file.Paths;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Service
@Slf4j
public class FileServiceImpl implements FileService {

    @Value("${upload.directory}")
    private String uploadDirectory;

    @Autowired
    private StudentMapper studentMapper;
    @Autowired
    private PaperMapper paperMapper;
    @Autowired
    private TeacherMapper teacherMapper;

    /**
     * 学生上传头像
     *
     * @param id
     * @param image
     * @return
     */
    @Override
    public Result uploadPortrait(String id, MultipartFile image) {
        if (image == null) {
            return Result.error("未获取到图像");
        }
        try {
            File imageFile = FileUtils.multipartFileToFile(image);
            if (!FileUtils.isImage(imageFile)) {
                return Result.error("上传的文件不是图片或不支持");
            }
            Student tempStudent = studentMapper.selectById(id);
            String oldPath = uploadDirectory + "/files/portraits/" + tempStudent.getAvatar();
            try {
                File oldFile = new File(oldPath);
                oldFile.delete();
            } catch (Exception e) {
                log.info("无法删除" + oldPath);
                return Result.error("上传失败");
            }
            //新图片
            String uuid = UUID.randomUUID().toString();
            tempStudent.setAvatar(uuid + ".jpg");
            String originalFilename = image.getOriginalFilename();
            String imagePath = uploadDirectory + "/files/portraits/" + uuid + ".jpg";
            String targetPath = imagePath;
            FileUtils.createFile(imagePath);
            image.transferTo(new File(imagePath));
            FileUtils.waterMarkByText("haichi", imagePath, targetPath, 3, 100, 100, 0F);
            log.info("头像缓存删除：" + imageFile.delete());
            studentMapper.updateById(tempStudent);
            log.info(id + "上传了头像" + originalFilename + "保存在" + targetPath);
            return Result.success("头像上传成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Result.error("头像上传失败");
        }


    }

    /**
     * 上传论文
     *
     * @param id
     * @param paper
     * @param file
     * @return
     */
    @Override
    public Result uploadPaper(String id, Paper paper, MultipartFile file) {
        String uuid = UUID.randomUUID().toString();
        paper.setId(uuid);
        paper.setStatus("审核中");
        paper.setCreatedAt(LocalDate.now());
        paper.setUpdatedAt(LocalDate.now());
        String fileName = file.getOriginalFilename();
        String fileType = fileName.substring(fileName.lastIndexOf(".") + 1);
        if(!(fileType.equals("pdf")||fileType.equals("doc")||fileType.equals("docx"))){
            return Result.error("文件格式不正确");
        }
//        if(!fileName.contains("已签字")){
//            return Result.error("论文未签字");
//        }
        paper.setType(fileType);
        paper.setSize((int) file.getSize());
        paper.setDownloadLink(uuid +"."+fileType);
        paper.setOwnerId(id);
        String filePath = uploadDirectory+ "/files/papers/"+uuid+"."+fileType;
        try {
            FileUtils.createFile(filePath);
            file.transferTo(Paths.get(filePath));
            log.info(id+"上传了论文在"+filePath);
            paperMapper.insert(paper);
        }catch (Exception e){
            e.printStackTrace();
            return Result.error("论文上传失败");
        }
//        paper.setOwnerId(id);
//        if(paper.getTitle()==null||paper.getTitle().equals("")){
//            return Result.error("标题不能为空");
//        }
//        Map<String, Object> titleMap = new HashMap<>();
//        titleMap.put("title",paper.getTitle());
//        titleMap.put("owner_id",paper.getOwnerId());
//        if(!paperMapper.selectByMap(titleMap).isEmpty()){
//            return Result.error("你已经上传过同名的论文了");
//        }
////        if(paper.getCollegeId()==null||paper.getCollegeId().equals("")){
////            return Result.error("学院不能为空");
////        }
//        if(paper.getTeacherId()==null||paper.getTeacherId().equals("")){
//            return Result.error("教师不能为空");
//        }
//        if(!file.getOriginalFilename().endsWith(".pdf")){
//            return Result.error("文件格式不正确");
//        }
//
//        try {
//            paper.setOwner(studentMapper.selectById(paper.getOwnerId()).getRealName());
//            paper.setTeacher(teacherMapper.selectById(paper.getTeacherId()).getName());
//        }catch (Exception e){
//            e.printStackTrace();
//            return Result.error("非法请求");
//        }
//
//        Student student = studentMapper.selectById(id);
//        String fileName = student.getId() +"+"+ student.getName() +"+"+ paper.getTitle()+".pdf";
//
//        String filePath = uploadDirectory + "/resources/" + id + "/papers/"+fileName;
//
//        try {
//            FileUtils.createFile(filePath);
//            file.transferTo(new File(filePath));
//            paperMapper.insert(paper);
//
//        } catch (IOException e) {
//            e.printStackTrace();
        return Result.success("文件上传成功");
    }
//        log.info(filePath);
//        return Result.success("文件上传成功");
//
//    }
}
